package com.begye.smartloan.apptest.tool

import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject

/**
 */
val printInterceptor: HttpLoggingInterceptor =
    HttpLoggingInterceptor(HttpLogInterceptor()).apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

/**
 */
class HttpLogInterceptor : HttpLoggingInterceptor.Logger {

    companion object {
        fun printJson(text: String?) {
            text?.let {
                try {
                    val json = JSONObject(it)
                    val jsonObject = JsonParser.parseString(json.toString()).asJsonObject
                    val gson = GsonBuilder().setPrettyPrinting().create()
                    val result = gson.toJson(jsonObject)
                    println(result)
                } catch (e: Exception) {
                    //
                }
            }
        }

        fun printJson(value: JSONObject?) {
            value?.let { json ->
                try {
                    val jsonObject = JsonParser.parseString(json.toString()).asJsonObject
                    val gson = GsonBuilder().setPrettyPrinting().create()
                    val result = gson.toJson(jsonObject)
                    println(result)
                } catch (e: Exception) {
                    //
                }
            }
        }
    }

    override fun log(message: String) {
        try {
            if (isJsonString(message)) {
                val json = JSONObject(message)
                val jsonObject = JsonParser.parseString(json.toString()).asJsonObject
                val gson = GsonBuilder().setPrettyPrinting().create()
                val result = gson.toJson(jsonObject)
                println(result)
            } else {
                println(message)
            }
        } catch (e: Exception) {
//            e.printStackTrace()
        }
    }

    private fun isJsonString(text: String?): Boolean {
        if (text.isNullOrBlank()) return false
        return try {
            JSONObject(text)
            true
        } catch (e: Exception) {
            false
        }
    }
}